package com.gxuwz.zhangjiahui.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zhangjiahui.entity.Role;
import com.gxuwz.zhangjiahui.entity.User;
import com.gxuwz.zhangjiahui.service.IRoleService;
import com.gxuwz.zhangjiahui.service.IUserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-06-20
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IRoleService iRoleService;


    /**
     * 查询全部用户信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @Pointcut
    @ResponseBody
    @RequestMapping(value = "/findUser")
    public ModelAndView findUser(ModelAndView modelAndView, Page page, Integer pageNumber, User user,
                                    @Param("userId") String userId,
                                    HttpServletRequest request, HttpServletResponse response) {
        if(request.getSession().getAttribute("nowResult") != null){
            if (!request.getSession().getAttribute("nowResult").equals("now")) {
                request.getSession().setAttribute("result", "");
            }
            request.getSession().setAttribute("nowResult", "");
        }
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("user_id");
        // 进行模糊查询!!!
        if(userId != null && userId != ""){
            wrapper.like("user_id", userId);
            request.getSession().setAttribute("userId", userId);
        }else {
            request.getSession().setAttribute("userId", "");
        }
        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 下拉框选择器
        if(user != null & user.getRoleId() != null){
            if(!user.getRoleId().equals("1000")){
                wrapper.eq("role_id", user.getRoleId());
            }
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<User> userIPage = iUserService.selectUserPage(page, wrapper);
        // 存放page，内有当前页数
        modelAndView.addObject("page", page);
        System.out.println("总条数"+userIPage.getTotal());
        System.out.println("总页数"+userIPage.getPages());
        // 存放总页数
        modelAndView.addObject("pages", (int)userIPage.getPages());
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)userIPage.getPages()];
        for(int i=0; i< (int)userIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        modelAndView.addObject("pagesList", pagesList);
        modelAndView.addObject("numberPages", userIPage.getTotal());
        List<User> userList = userIPage.getRecords();
        System.out.println("userList = "+userList);
        modelAndView.addObject("userList", userList);

        // role
        List<Role> roleList = iRoleService.findRoleAll();
        modelAndView.addObject("roleList", roleList);

        modelAndView.setViewName("user/user_list");
        return modelAndView;
    }



    /**
     * 添加用户信息 / 修改用户信息
     * @param user
     * @return
     */
    @PostMapping(value = "/addEditUser")
    public ModelAndView addEditUser(User user, HttpServletRequest request, ModelAndView modelAndView) {
        User user1 = iUserService.findUserById(user);
        System.out.println("user = " + user);
        System.out.println("user1 = " + user1);
        // 新增用户信息
        if(user1 == null){
            System.out.println("进入新增用户");
            try {
                iUserService.addUser(user);
                request.getSession().setAttribute("result", "addTrue");
                request.getSession().setAttribute("nowResult", "now");
            }catch (Exception e){
                request.getSession().setAttribute("result", "addFalse");
                request.getSession().setAttribute("nowResult", "now");
            }
        }
        // 修改用户信息
        if(user1 != null){
            System.out.println("进入修改用户");
            try {
                iUserService.updateUserById(user);
                request.getSession().setAttribute("result", "editTrue");
                request.getSession().setAttribute("nowResult", "now");
            }catch (Exception e){
                request.getSession().setAttribute("result", "editFalse");
                request.getSession().setAttribute("nowResult", "now");
            }
        }
        modelAndView.setViewName("redirect:/user/findUser");
        return modelAndView;
    }



    /**
     * 删除用户信息
     * @param userId
     * @return
     */
    @GetMapping(value = "/deleteUser")
    public ModelAndView deleteUser(HttpServletRequest request, ModelAndView modelAndView,
                             @Param("userId") String userId) {
        User user = new User();
        user.setUserId(userId);
        try {
            iUserService.deleteUserById(user);
            request.getSession().setAttribute("result", "deleteTrue");
            request.getSession().setAttribute("nowResult", "now");
        }catch (Exception e){

        }
        modelAndView.setViewName("redirect:/user/findUser");
        return modelAndView;
    }


    /**
     * 打开用户个人信息界面
     * @param modelAndView
     * @return
     */
    @GetMapping(value = "/editUserAdmin")
    public ModelAndView editUserAdmin(ModelAndView modelAndView, HttpServletRequest request) {
        if(request.getSession().getAttribute("nowError") != null){
            if (!request.getSession().getAttribute("nowError").equals("now")) {
                request.getSession().setAttribute("error", "");
            }
            request.getSession().setAttribute("nowError", "");
        }
        User user = (User) request.getSession().getAttribute("user");
        modelAndView.addObject("user", user);
        modelAndView.setViewName("/user/user_me");
        return modelAndView;
    }


    /**
     * 用户修改个人信息
     * @param user
     * @return
     */
    @PostMapping(value = "/updateUserAdmin")
    public ModelAndView updateUserAdmin(ModelAndView modelAndView, User user, HttpServletRequest request,
                                   @Param("password_edit") String password_edit,
                                   @Param("confirm_password") String confirm_password) {
        String password = user.getPassWord();
        User user1 = iUserService.findUserById(user);
        if(user1.getPassWord().equals(password)){
            if(password_edit != "" && confirm_password != ""){
                if(password_edit.equals(confirm_password)){
                    user.setPassWord(confirm_password);
                    iUserService.updateUserById(user);
                    request.getSession().setAttribute("error", "true");
                    request.getSession().setAttribute("nowError", "now");
                }else {
                    request.getSession().setAttribute("error", "twoNewPwdNone");
                    request.getSession().setAttribute("nowError", "now");
                }
            }else {
                request.getSession().setAttribute("error", "newPwdNone");
                request.getSession().setAttribute("nowError", "now");
            }
        }else {
            request.getSession().setAttribute("error", "oldPwdError");
            request.getSession().setAttribute("nowError", "now");
        }
        modelAndView.setViewName("redirect:/user/editUserAdmin");
        return modelAndView;
    }

}
